package org.dromara.common.encrypt.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriBuilder;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.function.Function;

@Component
@RequiredArgsConstructor
public class WebClientUtil
{
    private final WebClient webClient;

    /**
     *
     * @param uri
     * @param body
     * @param clazz
     * @return
     * @param <T>
     * @param <R>
     */
    public <T,R> R post(String uri,T body,Class<R> clazz){
        return webClient.post()
            .uri(uri)
            .body(Mono.just(body), body.getClass())
            .retrieve()
            .bodyToMono(clazz)
            .block();
    }

    /**
     * get请求
     * @param uri 接口地址
     * @param clazz 返回的类型
     * @param params 请求参数 多个参数建议使用Map
     * @param function 请求参数拼接方法
     * @return 请求结果
     */
    public <T,R> R get(String uri, Class<R> clazz,T params ,Function<T,UriBuilder> function){
        return webClient.get()
            .uri(function.apply(params).build())
            .retrieve()
            .bodyToMono(clazz)
            .block();
    }
}
